package cn.hnh.service.impl;

import cn.hnh.constrant.ResultInfo;
import cn.hnh.mapper.ArticleMapper;
import cn.hnh.mapper.CategoriesMapper;
import cn.hnh.pojo.Categories;
import cn.hnh.service.CategoriesService;
import cn.hnh.utils.DateFormatUtils;
import cn.hnh.vo.ArticleTitleVo;
import cn.hnh.vo.CategoriesArticleVo;
import cn.hnh.vo.CategoriesVo;
import cn.hnh.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author HuangNianHong
 * @Time 2021/1/5
 */
@Service
public class CategoriesServiceImpl implements CategoriesService {
    @Autowired
    private CategoriesMapper categoriesMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Result<CategoriesVo> getCategoriesVo() {
        List<Categories> list = categoriesMapper.getCategories();
        if(list!=null){
            CategoriesVo res = new CategoriesVo();
            res.setCount(categoriesMapper.getCategoriesCount());
            List<CategoriesArticleVo> categoriesArticleVos=new CopyOnWriteArrayList<>();
            for (Categories categories : list) {
                CategoriesArticleVo categoriesArticleVo = new CategoriesArticleVo();
                categoriesArticleVo.setName(categories.getName());
                categoriesArticleVo.setCount(articleMapper.getArticleCountByCategoriesId(categories.getId()));
                categoriesArticleVos.add(categoriesArticleVo);
            }
            res.setInfo(categoriesArticleVos);
            return new Result<>(ResultInfo.SUCCESS_CODE,ResultInfo.SUCCESS_MESSAGE,res);
        }
        return new Result<>(ResultInfo.NOTFOUND_CODE,ResultInfo.NOTFOUND_MESSAGE);
    }

    @Override
    public Result<List<ArticleTitleVo>> getArticleTitleVoByCategoriesName(String categoriesName) {
        Integer id = categoriesMapper.getIdByName(categoriesName);
        if(id==null)
            return new Result<>(ResultInfo.NOTFOUND_CODE,ResultInfo.NOTFOUND_MESSAGE);
        List<ArticleTitleVo> list = articleMapper.getArticleTitleByCategoriesId(id);
        for (ArticleTitleVo articleTitleVo : list) {
            articleTitleVo.setDate(DateFormatUtils.formatDate(articleTitleVo.getTime()));
        }
        return new Result<>(ResultInfo.SUCCESS_CODE,ResultInfo.SUCCESS_MESSAGE,list);
    }
}
